

import React, { useState, useEffect, useRef } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import styles from './styles.module.css';

interface ContentData {
  title: string;
  author: string;
  date: string;
  views: string;
  duration: string;
  category: string;
  difficulty: string;
  videoUrl: string;
  poster: string;
  progress: number;
  likes: number;
  bookmarked: boolean;
  description: string;
}

interface Comment {
  id: string;
  author: string;
  avatar: string;
  time: string;
  content: string;
  likes: number;
  isLiked: boolean;
  replies?: Reply[];
}

interface Reply {
  id: string;
  author: string;
  avatar: string;
  time: string;
  content: string;
}

interface RelatedContent {
  id: string;
  title: string;
  description: string;
  thumbnail: string;
  category: string;
  views: string;
}

const ContentDetailPage: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [isLiked, setIsLiked] = useState(false);
  const [isBookmarked, setIsBookmarked] = useState(false);
  const [likeCount, setLikeCount] = useState(856);
  const [commentText, setCommentText] = useState('');
  const [progress, setProgress] = useState(65);
  const [totalComments, setTotalComments] = useState(23);
  const videoRef = useRef<HTMLVideoElement>(null);

  // 模拟内容数据
  const contentData: Record<string, ContentData> = {
    '1': {
      title: '批判性思维：如何建立理性思考框架',
      author: '李教授',
      date: '2024年1月15日',
      views: '12,543',
      duration: '25分钟',
      category: '认知提升',
      difficulty: '进阶',
      videoUrl: 'https://s.coze.cn/image/z1S6IQEt2NU/',
      poster: 'https://s.coze.cn/image/Ht_E7iDZfc8/',
      progress: 65,
      likes: 856,
      bookmarked: true,
      description: '批判性思维是现代社会不可或缺的核心能力。本课程将系统介绍批判性思维的基本原则、方法和实践技巧...'
    },
    '2': {
      title: '第一性原理：从根本上解决问题的思维方法',
      author: '王教授',
      date: '2024年1月12日',
      views: '8,923',
      duration: '20分钟',
      category: '认知提升',
      difficulty: '专家',
      videoUrl: 'https://s.coze.cn/image/rxnqklPRfI8/',
      poster: 'https://s.coze.cn/image/vLSvVoN3Ulw/',
      progress: 30,
      likes: 623,
      bookmarked: false,
      description: '学习埃隆·马斯克的思维模式，掌握从本质出发的创新思考方法...'
    },
    '3': {
      title: '系统思维：复杂问题的分析与解决',
      author: '张博士',
      date: '2024年1月10日',
      views: '15,678',
      duration: '30分钟',
      category: '认知提升',
      difficulty: '进阶',
      videoUrl: 'https://s.coze.cn/image/xP04OYlKQME/',
      poster: 'https://s.coze.cn/image/v8iY-Wv9xrY/',
      progress: 0,
      likes: 1245,
      bookmarked: false,
      description: '学会用系统的视角看待问题，掌握整体分析和解决复杂问题的能力...'
    }
  };

  const [currentContent, setCurrentContent] = useState<ContentData>(contentData['1']);

  const [comments, setComments] = useState<Comment[]>([
    {
      id: '1',
      author: '王同学',
      avatar: 'https://s.coze.cn/image/43PDaXpY5nA/',
      time: '2天前',
      content: '非常棒的课程！教授讲解得很清晰，案例也很实用。学完之后我开始有意识地运用批判性思维来分析问题，确实感觉思考质量有了明显提升。',
      likes: 12,
      isLiked: false,
      replies: [
        {
          id: '1-1',
          author: '张三',
          avatar: 'https://s.coze.cn/image/XMipe5fGecM/',
          time: '1天前',
          content: '同感！特别是逻辑谬误识别那部分，让我意识到自己以前犯了很多思维错误。'
        }
      ]
    },
    {
      id: '2',
      author: '李经理',
      avatar: 'https://s.coze.cn/image/1_f1gGoYZ7c/',
      time: '3天前',
      content: '作为一名管理者，我觉得批判性思维对决策质量至关重要。这门课程提供了很多实用的工具和方法，推荐给所有需要做决策的人。',
      likes: 8,
      isLiked: false
    },
    {
      id: '3',
      author: '张老师',
      avatar: 'https://s.coze.cn/image/YRUiZJmqV3w/',
      time: '5天前',
      content: '内容很专业，结构清晰，适合系统性学习。建议增加一些练习题，帮助巩固所学知识。',
      likes: 15,
      isLiked: false
    }
  ]);

  const relatedContents: RelatedContent[] = [
    {
      id: '2',
      title: '第一性原理：从根本上解决问题的思维方法',
      description: '学习埃隆·马斯克的思维模式，掌握从本质出发的创新思考方法。',
      thumbnail: 'https://s.coze.cn/image/niNKVwLGT5Q/',
      category: '认知提升',
      views: '1.2万次观看'
    },
    {
      id: '3',
      title: '系统思维：复杂问题的分析与解决',
      description: '学会用系统的视角看待问题，掌握整体分析和解决复杂问题的能力。',
      thumbnail: 'https://s.coze.cn/image/PLqWzyU2AjU/',
      category: '认知提升',
      views: '8.9千次观看'
    },
    {
      id: '4',
      title: '决策科学：理性决策的心理学原理',
      description: '了解决策背后的心理学机制，提高决策质量和效率。',
      thumbnail: 'https://s.coze.cn/image/2TT5p1szwm8/',
      category: '认知提升',
      views: '15.6万次观看'
    }
  ];

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = currentContent.title + ' - 精进坊';
    return () => {
      document.title = originalTitle;
    };
  }, [currentContent.title]);

  // 加载内容数据
  useEffect(() => {
    const contentId = searchParams.get('id') || '1';
    const content = contentData[contentId] || contentData['1'];
    setCurrentContent(content);
    setLikeCount(content.likes);
    setIsBookmarked(content.bookmarked);
    setProgress(content.progress);
  }, [searchParams]);

  // 视频播放进度更新
  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const handleTimeUpdate = () => {
      if (video.duration > 0) {
        const newProgress = Math.floor((video.currentTime / video.duration) * 100);
        setProgress(newProgress);
      }
    };

    video.addEventListener('timeupdate', handleTimeUpdate);
    return () => {
      video.removeEventListener('timeupdate', handleTimeUpdate);
    };
  }, []);

  const handleSearchKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      const keyword = (e.target as HTMLInputElement).value.trim();
      if (keyword) {
        navigate(`/search-result?q=${encodeURIComponent(keyword)}`);
      }
    }
  };

  const handleLikeClick = () => {
    if (isLiked) {
      setLikeCount(prev => prev - 1);
    } else {
      setLikeCount(prev => prev + 1);
    }
    setIsLiked(!isLiked);
  };

  const handleBookmarkClick = () => {
    setIsBookmarked(!isBookmarked);
  };

  const handleShareClick = () => {
    alert('分享功能');
  };

  const handleRelatedContentClick = (contentId: string) => {
    navigate(`/content-detail?id=${contentId}`);
  };

  const handleSubmitComment = () => {
    const trimmedComment = commentText.trim();
    if (trimmedComment) {
      console.log('发表评论:', trimmedComment);
      setCommentText('');
      alert('评论发表成功！');
    } else {
      alert('请输入评论内容');
    }
  };

  const handleCommentLike = (commentId: string) => {
    setComments(prevComments =>
      prevComments.map(comment => {
        if (comment.id === commentId) {
          return {
            ...comment,
            isLiked: !comment.isLiked,
            likes: comment.isLiked ? comment.likes - 1 : comment.likes + 1
          };
        }
        return comment;
      })
    );
  };

  const handleCommentReply = (commentId: string) => {
    console.log('回复评论:', commentId);
  };

  const handleLoadMoreComments = () => {
    console.log('加载更多评论');
  };

  const handleSocialShare = (platform: string) => {
    console.log(`分享到${platform}`);
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 顶部导航栏 */}
      <header className="fixed top-0 left-0 right-0 h-16 bg-white shadow-sm z-50">
        <div className="flex items-center justify-between h-full px-6">
          {/* Logo和产品名称 */}
          <div className="flex items-center space-x-3">
            <div className={`w-10 h-10 ${styles.gradientBg} rounded-xl flex items-center justify-center`}>
              <i className="fas fa-graduation-cap text-white text-lg"></i>
            </div>
            <h1 className="text-xl font-bold text-text-primary">精进坊</h1>
          </div>
          
          {/* 主导航 */}
          <nav className="hidden md:flex items-center space-x-8">
            <Link to="/home" className="px-4 py-2 rounded-lg text-center text-text-secondary hover:text-secondary">首页</Link>
            <Link to="/cognition-home" className={`px-4 py-2 rounded-lg text-center ${styles.navActive}`}>认知提升</Link>
            <Link to="/fitness-home" className="px-4 py-2 rounded-lg text-center text-text-secondary hover:text-secondary">身体健身</Link>
            <Link to="/learning-home" className="px-4 py-2 rounded-lg text-center text-text-secondary hover:text-secondary">学习能力</Link>
          </nav>
          
          {/* 搜索框和用户操作区 */}
          <div className="flex items-center space-x-4">
            {/* 搜索框 */}
            <div className="relative hidden lg:block">
              <input 
                type="text" 
                placeholder="搜索内容..." 
                className="w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
                onKeyPress={handleSearchKeyPress}
              />
              <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
            </div>
            
            {/* 消息通知 */}
            <button className="relative p-2 text-gray-600 hover:text-secondary">
              <i className="fas fa-bell text-lg"></i>
              <span className="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full"></span>
            </button>
            
            {/* 用户头像/昵称 */}
            <div className="relative">
              <Link to="/user-profile" className="flex items-center space-x-2 p-2 rounded-lg hover:bg-gray-100">
                <img 
                  src="https://s.coze.cn/image/G4k9bQoc_AM/" 
                  alt="用户头像" 
                  className="w-8 h-8 rounded-full" 
                />
                <span className="hidden md:block text-text-primary font-medium">张三</span>
                <i className="fas fa-chevron-down text-xs text-gray-400"></i>
              </Link>
            </div>
          </div>
        </div>
      </header>

      {/* 主布局容器 */}
      <div className="pt-16 min-h-screen">
        {/* 主内容区 */}
        <main className="p-6">
          {/* 页面头部 */}
          <div className="mb-6">
            <nav className="text-sm text-text-secondary mb-4">
              <Link to="/home" className="hover:text-secondary">首页</Link>
              <span className="mx-2">{'>'}</span>
              <Link to="/cognition-home" className="hover:text-secondary">认知提升</Link>
              <span className="mx-2">{'>'}</span>
              <span className="text-text-primary">{currentContent.title}</span>
            </nav>
          </div>

          {/* 内容详情卡片 */}
          <div className={`${styles.contentCard} rounded-card shadow-card mb-8`}>
            {/* 内容头部 */}
            <div className="p-6 border-b border-gray-100">
              <div className="flex items-start justify-between mb-4">
                <div className="flex-1">
                  <h1 className="text-3xl font-bold text-text-primary mb-4">{currentContent.title}</h1>
                  <div className="flex items-center space-x-6 text-sm text-text-secondary">
                    <div className="flex items-center space-x-2">
                      <img 
                        src="https://s.coze.cn/image/v1ExTXE3EkY/" 
                        alt="作者头像" 
                        className="w-6 h-6 rounded-full" 
                      />
                      <span>{currentContent.author}</span>
                    </div>
                    <span><i className="fas fa-calendar mr-1"></i>{currentContent.date}</span>
                    <span><i className="fas fa-eye mr-1"></i>{currentContent.views} 次观看</span>
                    <span><i className="fas fa-clock mr-1"></i>{currentContent.duration}</span>
                  </div>
                </div>
                <div className="flex items-center space-x-2">
                  <span className="bg-secondary text-white px-3 py-1 rounded-full text-sm">{currentContent.category}</span>
                  <span className="bg-green-100 text-green-600 px-3 py-1 rounded-full text-sm">{currentContent.difficulty}</span>
                </div>
              </div>
            </div>

            {/* 视频播放器区域 */}
            <div className="p-6 border-b border-gray-100">
              <div className={`${styles.videoContainer} mb-4`}>
                <video 
                  ref={videoRef}
                  className={styles.videoPlayer}
                  controls 
                  poster={currentContent.poster}
                >
                  <source src={currentContent.videoUrl} type="video/mp4" />
                  您的浏览器不支持视频播放。
                </video>
              </div>
              
              {/* 学习进度条 */}
              <div className="mb-4">
                <div className="flex items-center justify-between text-sm text-text-secondary mb-2">
                  <span>学习进度</span>
                  <span>{progress}%</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div 
                    className={`${styles.progressBar} h-2 rounded-full`} 
                    style={{ width: `${progress}%` }}
                  ></div>
                </div>
              </div>

              {/* 互动操作区 */}
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-6">
                  <button 
                    onClick={handleLikeClick}
                    className={`flex items-center space-x-2 px-4 py-2 rounded-lg hover:bg-gray-100 transition-colors ${isLiked ? styles.likeBtnLiked : ''}`}
                  >
                    <i className="fas fa-heart text-lg"></i>
                    <span>{likeCount}</span>
                  </button>
                  <button 
                    onClick={handleBookmarkClick}
                    className={`flex items-center space-x-2 px-4 py-2 rounded-lg hover:bg-gray-100 transition-colors ${isBookmarked ? styles.bookmarkBtnBookmarked : ''}`}
                  >
                    <i className="fas fa-bookmark text-lg"></i>
                    <span>收藏</span>
                  </button>
                  <button 
                    onClick={handleShareClick}
                    className="flex items-center space-x-2 px-4 py-2 rounded-lg hover:bg-gray-100 transition-colors"
                  >
                    <i className="fas fa-share text-lg"></i>
                    <span>分享</span>
                  </button>
                </div>
                <div className="flex items-center space-x-2">
                  <button 
                    onClick={() => handleSocialShare('微信')}
                    className="p-2 text-green-500 hover:bg-green-100 rounded-lg"
                  >
                    <i className="fab fa-weixin text-lg"></i>
                  </button>
                  <button 
                    onClick={() => handleSocialShare('微博')}
                    className="p-2 text-red-500 hover:bg-red-100 rounded-lg"
                  >
                    <i className="fab fa-weibo text-lg"></i>
                  </button>
                  <button 
                    onClick={() => handleSocialShare('QQ')}
                    className="p-2 text-blue-500 hover:bg-blue-100 rounded-lg"
                  >
                    <i className="fab fa-qq text-lg"></i>
                  </button>
                </div>
              </div>
            </div>

            {/* 内容描述 */}
            <div className="p-6 border-b border-gray-100">
              <h3 className="text-lg font-semibold text-text-primary mb-3">课程简介</h3>
              <p className="text-text-secondary leading-relaxed">
                批判性思维是现代社会不可或缺的核心能力。本课程将系统介绍批判性思维的基本原则、方法和实践技巧，帮助你建立理性思考的框架，学会独立分析问题、评估信息、做出明智决策。通过大量案例分析和实战练习，你将掌握如何识别逻辑谬误、评估证据质量、构建合理论证，从而在工作和生活中做出更明智的判断。
              </p>
            </div>

            {/* 课程大纲 */}
            <div className="p-6 border-b border-gray-100">
              <h3 className="text-lg font-semibold text-text-primary mb-3">课程大纲</h3>
              <div className="space-y-3">
                <div className="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-50">
                  <div className="w-8 h-8 bg-secondary text-white rounded-full flex items-center justify-center text-sm font-medium">1</div>
                  <div className="flex-1">
                    <h4 className="font-medium text-text-primary">批判性思维的基本概念</h4>
                    <p className="text-sm text-text-secondary">了解批判性思维的定义、重要性和核心要素</p>
                  </div>
                  <span className="text-sm text-text-secondary">15分钟</span>
                </div>
                <div className="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-50">
                  <div className="w-8 h-8 bg-secondary text-white rounded-full flex items-center justify-center text-sm font-medium">2</div>
                  <div className="flex-1">
                    <h4 className="font-medium text-text-primary">逻辑谬误识别技巧</h4>
                    <p className="text-sm text-text-secondary">学会识别常见的逻辑谬误和思维陷阱</p>
                  </div>
                  <span className="text-sm text-text-secondary">20分钟</span>
                </div>
                <div className="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-50">
                  <div className="w-8 h-8 bg-secondary text-white rounded-full flex items-center justify-center text-sm font-medium">3</div>
                  <div className="flex-1">
                    <h4 className="font-medium text-text-primary">证据评估方法</h4>
                    <p className="text-sm text-text-secondary">掌握如何评估信息来源的可靠性和证据质量</p>
                  </div>
                  <span className="text-sm text-text-secondary">25分钟</span>
                </div>
                <div className="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-50">
                  <div className="w-8 h-8 bg-secondary text-white rounded-full flex items-center justify-center text-sm font-medium">4</div>
                  <div className="flex-1">
                    <h4 className="font-medium text-text-primary">论证构建与评估</h4>
                    <p className="text-sm text-text-secondary">学习如何构建有效的论证和评估他人的论证</p>
                  </div>
                  <span className="text-sm text-text-secondary">30分钟</span>
                </div>
              </div>
            </div>
          </div>

          {/* 相关推荐 */}
          <div className={`${styles.contentCard} rounded-card shadow-card mb-8`}>
            <div className="p-6">
              <h3 className="text-lg font-semibold text-text-primary mb-4">相关推荐</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {relatedContents.map((item) => (
                  <div 
                    key={item.id}
                    onClick={() => handleRelatedContentClick(item.id)}
                    className={`${styles.contentCard} rounded-lg shadow-sm p-4 ${styles.cardHover} cursor-pointer`}
                  >
                    <div className="flex space-x-3">
                      <img 
                        src={item.thumbnail} 
                        alt="相关内容缩略图" 
                        className="w-16 h-16 object-cover rounded-lg" 
                      />
                      <div className="flex-1">
                        <h4 className="font-medium text-text-primary mb-1 line-clamp-2">{item.title}</h4>
                        <p className="text-sm text-text-secondary line-clamp-2">{item.description}</p>
                        <div className="flex items-center justify-between mt-2 text-xs text-text-secondary">
                          <span>{item.category}</span>
                          <span>{item.views}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* 评论区 */}
          <div className={`${styles.contentCard} rounded-card shadow-card`}>
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-lg font-semibold text-text-primary">评论区</h3>
                <span className="text-sm text-text-secondary">共 <span>{totalComments}</span> 条评论</span>
              </div>

              {/* 发表评论 */}
              <div className="mb-6 p-4 bg-gray-50 rounded-lg">
                <div className="flex space-x-3">
                  <img 
                    src="https://s.coze.cn/image/bcPGVvaUf2U/" 
                    alt="用户头像" 
                    className="w-10 h-10 rounded-full" 
                  />
                  <div className="flex-1">
                    <textarea 
                      value={commentText}
                      onChange={(e) => setCommentText(e.target.value)}
                      placeholder="分享你的想法..." 
                      className="w-full p-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent resize-none"
                      rows={3}
                    />
                    <div className="flex items-center justify-end mt-3">
                      <button 
                        onClick={handleSubmitComment}
                        className="px-6 py-2 bg-secondary text-white rounded-lg hover:bg-accent transition-colors"
                      >
                        发表评论
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              {/* 评论列表 */}
              <div className="space-y-4">
                {comments.map((comment) => (
                  <div key={comment.id} className={`${styles.commentItem} p-4`}>
                    <div className="flex space-x-3">
                      <img 
                        src={comment.avatar} 
                        alt="评论者头像" 
                        className="w-8 h-8 rounded-full" 
                      />
                      <div className="flex-1">
                        <div className="flex items-center space-x-2 mb-1">
                          <span className="font-medium text-text-primary">{comment.author}</span>
                          <span className="text-xs text-text-secondary">{comment.time}</span>
                        </div>
                        <p className="text-text-primary mb-3">{comment.content}</p>
                        <div className="flex items-center space-x-4">
                          <button 
                            onClick={() => handleCommentLike(comment.id)}
                            className={`flex items-center space-x-1 text-sm text-text-secondary hover:text-red-500 ${comment.isLiked ? 'text-red-500' : ''}`}
                          >
                            <i className={`${comment.isLiked ? 'fas' : 'far'} fa-heart`}></i>
                            <span>{comment.likes}</span>
                          </button>
                          <button 
                            onClick={() => handleCommentReply(comment.id)}
                            className="text-sm text-text-secondary hover:text-secondary"
                          >
                            回复
                          </button>
                        </div>
                        
                        {/* 回复列表 */}
                        {comment.replies && comment.replies.length > 0 && (
                          <div className="mt-3 pl-4 border-l-2 border-gray-200 space-y-3">
                            {comment.replies.map((reply) => (
                              <div key={reply.id} className="flex space-x-2">
                                <img 
                                  src={reply.avatar} 
                                  alt="回复者头像" 
                                  className="w-6 h-6 rounded-full" 
                                />
                                <div className="flex-1">
                                  <div className="flex items-center space-x-2 mb-1">
                                    <span className="font-medium text-text-primary text-sm">{reply.author}</span>
                                    <span className="text-xs text-text-secondary">{reply.time}</span>
                                  </div>
                                  <p className="text-text-primary text-sm">{reply.content}</p>
                                </div>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {/* 加载更多评论 */}
              <div className="text-center mt-6">
                <button 
                  onClick={handleLoadMoreComments}
                  className="px-6 py-2 border border-gray-200 text-text-secondary rounded-lg hover:bg-gray-50 transition-colors"
                >
                  加载更多评论
                </button>
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
};

export default ContentDetailPage;

